<?php

/**
 * @version			$Id$
 * @create 			2013-11-17 18:11:51 By xjiujiu
 * @description     HongJuZi Framework
 * @copyRight 		Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 */
defined('_HEXEC') or die('Restricted access!');

//导入引用文件
HClass::import('config.popo.userpopo, app.public.action.publicadminaction, model.usermodel');

/**
 * 用户扩展信息处理的动作类 
 * 
 * 主要处理主页的相关请求动作 
 * 
 * @author 			xjiujiu <xjiujiu@foxmail.com>
 * @package 		app.public.action
 * @since 			1.0.0
 */
class UserAction extends PublicadminAction
{

    private $_user;

    /**
     * 构造函数 
     * 
     * 初始化类里的变量 
     * 
     * @access public
     */
    public function __construct() 
    {
        $this->_popo    = new UserPopo();
        $this->_model   = new UserModel($this->_popo);
        $this->_userId  = HSession::getAttribute('id', 'user');
        AuserAction::isLogined();  
    }

    /**
     * 得到用户的信息
     * @return [type] [description]
     */
    public function getuserinfo()
    {
        HVerify::isAjax();
        $id     = HRequest::getParameter('id');
        if($id != HSession::getAttribute('id', 'user')) {
            throw new HRequestException('用户请求错误');
        }
        $record     = $this->_model->getRecordById($id);

        HResponse::json(array('rs'=>true, 'data'=> $record));
    }
   
    /**
     * 保存头像
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     */
    public function saveavatar()
    {
        HClass::import('hongjuzi.filesystem.hdir');
        $result             = array();
        $result['success']  = false;
        if(empty($_FILES)) {
            HResponse::json($result);
            exit;
        }
        //定义一个变量用以储存当前头像的序号
        $i                  = 1;
        $msg                = '';
        $maxSize            = 0.2 * 1024 * 1024; //单位Bytes
        $type               = 'image/jpeg|application/x-jpg|image/pjpeg';
        $avatarPathPrefix   = HFile::getAvatarPathByUserIdPrefix(HSession::getAttribute('id', 'user'));
        //遍历所有文件域
        while (list($key, $val) = each($_FILES)) {
            if($_FILES[$key]['error'] > 0) {
                $msg    .= $_FILES[$key]['error'];
                continue;
            }
            if($maxSize < $_FILES[$key]['size']) {
                $msg    .= '第' . $i .'张头像文件太大';
                continue;
            }
            if(false === strpos($type, $_FILES[$key]['type'])) {
                $msg    .= '第' . $i .'张头像文件类型不对！';
                continue;
            }
            //原始图片(file 域的名称：__source，如果客户端定义可以上传的话，可在此处理）。
            if($key == '__source') {
                $_FILES['image_path']   = $_FILES['__source'];
                try {
                    $this->_uploadFile();
                    $successNum++;
                } catch(Exception $ex) {
                    $msg    .= $ex->getMessage();
                }
                continue;
            }
            //头像图片(file 域的名称：__avatar1,2,3...)。
            $filePath   = HObject::GC('RES_DIR') . '/user/' . $avatarPathPrefix . $i . '.jpg';
            HDir::create(dirname($filePath));
            move_uploaded_file($_FILES[$key]['tmp_name'], ROOT_DIR . $filePath);
            $result['avatarUrls'][$i] = HResponse::url() . $filePath;
            $result['success'] = true;
            $i ++;
        }
        $result['message'] = $msg;
        //返回图片的保存结果（返回内容为json字符串）
        HResponse::json($result);
    }

    /**
     * 更新用户基本信息
     * @return [type] [description]
     */
    public function updatebaseinfo()
    {
        HVerify::isEmpty(HRequest::getParameter('name'));
        $interest   = HRequest::getParameter('interest');
        $this->_addInterestUser($interest);
        if(1 > $this->_model->edit(HPopoHelper::getUpdateFieldsAndValues($this->_model->getPopo()))) {
            throw new HRequestException('更新失败，请稍后再试');
        }
        HSession::setAttribute('name', HRequest::getParameter('name'), 'user');
        HResponse::redirect(HResponse::url('muser/editinfo' ,'' ,'cms'));
    }

    /**
     * 修改密码
     * @return [type] [description]
     */
    public function updateuserpwd()
    {
        $newPwd     = HRequest::getParameter('newpwd');
        $record     = $this->_model->getRecordById(HSession::getAttribute('id', 'user'));
        if(!$record) {
            throw new HVerifyException('用户不存在！');
        }
        if(HSession::getAttribute('password', 'user')) {
            $oldPwd     = HRequest::getParameter('oldpwd');
            $oldPwd     = $this->_encodePassword($oldPwd, $record['salt']);
            if($record['password'] != $oldPwd) {
                throw new HRequestException('旧密码错误');
            }
        }
        $data   = array('password' => $this->_encodePassword($newPwd, $record['salt']));
        if(1 > $this->_model->editByWhere($data, '`id` = ' . $record['id'])) {
            throw new HRequestException('修改密码失败，请稍后再试');
        }
        HSession::destroy();
        $url    = HResponse::url('enter', '', 'cms');
        if(HRequest::getParameter('from') == 'mobile') {
            $url    = HResponse::url('enter', '', 'mobile');
        }
        HResponse::succeed('修改密码成功，请您重新登录～', $url);
    }

    /**
     * 得到学校列表
     * @return [type] [description]
     */
    public function agetcollegelist()
    {
        $id     = HRequest::getParameter('id');
        if(!$id) {
            throw new HRequestException('请求省份id为空');
        }
        $list   = HClass::quickLoadModel('college')->getAllRowsByFields(
            '`id`, `name`', '`parent_id` = ' . $id
        );

        HResponse::json(array('rs' => true, 'data' => $list));
    }

    /**
     * 得到专业列表
     * @return [type] [description]
     */
    public function agetzhuanyelist()
    {
        $id     = HRequest::getParameter('id');
        if(!$id) {
            throw new HRequestException('请求大学id为空');
        }
        $list   = HClass::quickLoadModel('zhuanye')->getAllRowsByFields(
            '`id`, `name`', '`parent_id` = ' . $id
        );
        
        HResponse::json(array('rs' => true, 'data' => $list));
    }

}

?>
